
package net.dgg.rz.common.utils;


import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * ServleUtil工具类
 *<p>@Package: net.dgg.icass.tool.common.util</p>
 *<p>@Title：ServletUtil</p>
 *<p>@description:</p>
 *<p>@author liulei</p>
 *<p>@date 2018年5月2日</p>
 *<p>@Company dgg</p>
 */
public class ServletUtil implements ServletContextAware{
		
	private static ServletContext servletContext;
	
	/**
	 * 获取ServletContext
	 * @return
	 */
	public static ServletContext getServletContext(){
		return servletContext;
	}
	/**
	 * 获取ServletContext保存的数据
	 * @param name
	 * @return
	 */
	public static void setServletContextAttribute(String name,Object object){
		servletContext.setAttribute(name, object);
	}
	/**
	 * 获取ServletContext保存的数据
	 * @param name
	 * @return
	 */
	public static Object getServletContextAttribute(String name){
		return servletContext.getAttribute(name);
		
	}
	/**
	 * 获取HttpServletRequest
	 * @return
	 */
	public static HttpServletRequest getRequest(){
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

	}
	/**
	 * 获取HttpServletResponse
	 * @return
	 */
	public static HttpServletResponse getResponse(){
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();

	}
	/**
	 * 获取HttpServletRequest 保存的数据
	 * @param name
	 * @return
	 */
	public static Object getRequestAttribute(String name){
		
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getAttribute(name);

	}
	/**
	 * 获取ApplicationContext 
	 * @return
	 * @return
	 */
	public static ApplicationContext getApplicationContext(){
		
		return WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);	
	}
	/**
	 * 判断需要返回的信息格式是不是json
	 * @param request
	 * @return
	 */
	public static  boolean isJSONResponse(HttpServletRequest request){
		//根据Accept 类型判断返回的信息格式 
		String accept=request.getHeader("Accept");
		if(accept==null){
			return true;//如果Accept 为空 则返回 json格式
		}else{
			if(accept.contains("application/json")){
				return true;
			}else if("1".equals(request.getParameter("ajax"))){
				//iframe方式上传表单，默认隐藏提交一个ajax参数
				return true;
			}
		}
		return false;
	}
	@Override
	public void setServletContext(ServletContext arg0) {
		 servletContext=arg0;
	}

	
	
	
}
